#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <unistd.h>

#define SHM_KEY 1234
#define SEM_KEY 5678
#define SHM_SIZE 512

struct shmseg {
    int written;
    char text[SHM_SIZE];
};

void sem_wait(int semid) {
    struct sembuf sb = {0, -1, 0};
    semop(semid, &sb, 1);
}

void sem_signal(int semid) {
    struct sembuf sb = {0, 1, 0};
    semop(semid, &sb, 1);
}

int main() {
    int shmid, semid;
    struct shmseg *shm;

    shmid = shmget(SHM_KEY, sizeof(struct shmseg), 0666);
    if (shmid == -1) {
        perror("shmget failed");
        exit(1);
    }

    semid = semget(SEM_KEY, 1, 0666);
    if (semid == -1) {
        perror("semget failed");
        exit(1);
    }

    shm = (struct shmseg *) shmat(shmid, NULL, 0);
    if (shm == (void *) -1) {
        perror("shmat failed");
        exit(1);
    }

    while (1) {
        sem_wait(semid);
        if (shm->written == 1) {
            printf("Received: %s", shm->text);
            shm->written = 0;
        }
        sem_signal(semid);
        sleep(1);
    }

    return 0;
}
